package framework.utils.http;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Http request implementation
 *
 * @author Orlin Tomov
 * @version 0.2
 */
public class HttpRequest extends Http {

	/** constructor */
	public HttpRequest() {
	}

	/**
	 * Construct the request object and adds GET command
	 *
	 * @param	link	to get
	 */
	public HttpRequest(String link, boolean post, String HTTP) {
		if (post) {
			add(POST + " " + link.replaceAll(" ", "%20") + " " + HTTP_1_1);
		} else {
			if (HTTP == null) {
				add(GET + " " + link.replaceAll(" ", "%20") + " " + HTTP_1_0);
			} else {
				add(GET + " " + link.replaceAll(" ", "%20") + " " + HTTP);
			}
		}
		add("Date: " + new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z").format(new Date()));
	}

	/**
	 * Extracts range from value
	 *
	 * @return	range from value
	 */
	public int getRangeFrom() {
		for (int i = 0; i < lines.size(); i++) {
			//System.out.println("obj:"+lines.get(i));
			if (lines.get(i) instanceof String) {
				String line = (String)lines.get(i);
				//System.out.println("line:"+line);
				if (line.startsWith(RANGE_BYTES)) {
					String from = line.substring(RANGE_BYTES.length());
					from = from.substring(0, from.indexOf("-"));
					return Integer.parseInt(from);
				}
			}
		}
		return -1;
	}

	/**
	 * Extracts range to value
	 *
	 * @return	range to value
	 */
	public int getRangeTo() {
		for (int i = 0; i < lines.size(); i++) {
			//System.out.println("obj:"+lines.get(i));
			if (lines.get(i) instanceof String) {
				String line = (String)lines.get(i);
				//System.out.println("line:"+line);
				if (line.startsWith(RANGE_BYTES)) {
					String to = line.substring(RANGE_BYTES.length());
					to = to.substring(to.indexOf("-") + 1);
					return Integer.parseInt(to);
				}
			}
		}
		return -1;
	}

	/**
	 * Extract user value
	 *
	 * @return	user value
	 */
	public String getUser() {
		for (int i = 0; i < lines.size(); i++) {
			//System.out.println("obj:"+lines.get(i));
			if (lines.get(i) instanceof String) {
				String line = (String)lines.get(i);
				//System.out.println("line:"+line);
				if (line.startsWith(USER_AGENT)) {
					return line.substring(USER_AGENT.length());
				}
			}
		}
		return "";
	}
}
